/**
 * 
 */
package com.baijia.tianxiao.connect.handler;

import java.io.IOException;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.PongMessage;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import com.alibaba.fastjson.JSON;
import com.baijia.tianxiao.connect.config.Constants;
import com.baijia.tianxiao.connect.route.api.enums.MsgType;
import com.baijia.tianxiao.connect.route.api.model.DefaultCCMessage;
import com.baijia.tianxiao.connect.util.TianxiaoConnectUtil;
import com.baijia.tianxiao.connect.util.TianxiaoInnerConnectUtil;

/**
 * @author leiruiqi
 *
 */
public class TianxiaoInnerWebSocketHandler extends TextWebSocketHandler{
	
    private static Logger logger = LoggerFactory.getLogger(TianxiaoInnerWebSocketHandler.class); 

	@Resource
	private TianxiaoInnerConnectUtil tianxiaoInnerConnectUtil;
    

	public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
		String websocket_username = (String)session.getAttributes().get(Constants.SESSION_USERNAME);
		
		tianxiaoInnerConnectUtil.removeSession(session.getId()+"_"+websocket_username);
		
	}

	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		String websocket_username = (String)session.getAttributes().get(Constants.SESSION_USERNAME);
		session.getAttributes().put(Constants.LAST_MSG_TIME, System.currentTimeMillis());
		
		tianxiaoInnerConnectUtil.addSession(websocket_username+"_"+session.getId(), session);
		super.afterConnectionEstablished(session);
	}
	
	public void handleMessage(WebSocketSession session, WebSocketMessage<?> arg1) throws Exception {
		try {
			super.handleMessage(session, arg1);
		} catch (Exception e) {
			logger.error("do handleMessage exception ",e);
		}
	}

	protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
		logger.info("recieve message from session:"+session.getAttributes().get(Constants.SESSION_USERNAME)+",message:"+message);
		String messageStr = message.getPayload();
		DefaultCCMessage defaultCCMessage = null;
		try {
			defaultCCMessage = JSON.parseObject(messageStr, DefaultCCMessage.class);
		} catch (Exception e) {
			logger.error("JSON.parseObject exception",e);
			//throw new RuntimeException("Unexpected message ,can not tranport to JSON message: " + message);
			TextMessage returnmessage = new TextMessage("Unexpected message ,can not tranport to JSON message: "+message.getPayload());
			session.sendMessage(returnmessage);
			return;
		}
		if(defaultCCMessage==null){
			logger.error("JSON.parseObject exception null,messageStr="+messageStr);
			return;
		}
		String messagetype = defaultCCMessage.getType();
		if(StringUtils.isNoneBlank(messagetype)){
			session.getAttributes().put(Constants.LAST_MSG_TIME, System.currentTimeMillis());
		}
		if(StringUtils.equals(messagetype, MsgType.ping.name())){
			return;
		}
		
		if(StringUtils.equals(messagetype, MsgType.biz.name())){
			String sessionKey = defaultCCMessage.getMsgTo();
		}
		
	}

	

	protected void handlePongMessage(WebSocketSession session, PongMessage message) throws Exception {
		logger.info("receive pong ,user="+session.getAttributes().get(Constants.SESSION_USERNAME));
	}

	
	public void handleTransportError(WebSocketSession session, Throwable arg1) throws Exception {
		logger.info("handleTransportError session="+session.getAttributes().get(Constants.SESSION_USERNAME));
	}

	public boolean supportsPartialMessages() {
		// TODO Auto-generated method stub
		return false;
	}

	/** 
     * 给某个用户发送消息 
     * 
     * @param userName 
     * @param message 
     */  
	public void sendMessageToUser(String userSessionKey, TextMessage message) {
		WebSocketSession userSession = TianxiaoConnectUtil.getSession(userSessionKey);
		if (userSession!=null) {
			try {
				if (userSession.isOpen()) {
					userSession.sendMessage(message);
				}
			} catch (IOException e) {
				//e.printStackTrace();
				logger.error("",e);
			}
		}
	}
	
	
}
